<template>
  <div class="container-xl my-home-div">
    <!-- 头部信息区域 - 响应式布局 -->
    <div class="header-info">
      <div class="title-section">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-a-icon_FolderOpen"></use>
        </svg>
        <span class="title-text">资料</span>
      </div>

      <!-- 桌面端布局 -->
      <div class="desktop-stats">
        <div class="stat-item">
          <span class="stat-label"
            >容量：{{ useflow.usesize }} / {{ useflow.size }}</span
          >
          <div class="progress-wrapper">
            <el-progress :percentage="useflow.percentagesize" />
          </div>
        </div>
        <div class="stat-item">
          <span class="stat-label"
            >月流量：{{ useflow.useflow }} / {{ useflow.flow }}</span
          >
          <div class="progress-wrapper">
            <el-progress :percentage="useflow.percentageflow" />
          </div>
        </div>
        <div class="upload-section">
          <el-upload
            class="upload-demo"
            :disabled="!!percentage"
            action="https://jsonplaceholder.typicode.com/posts/"
            :auto-upload="true"
            :http-request="request"
            :show-file-list="false"
          >
            <el-button
              :disabled="!!percentage"
              ref="buttonRef"
              size="default"
              type="primary"
            >
              <el-icon :size="20">
                <Upload />
              </el-icon>
              &nbsp;
              {{ percentage ? "上传中..." + percentage + "%" : "上传文件" }}
            </el-button>
          </el-upload>
        </div>
      </div>

      <!-- 移动端布局 -->
      <div class="mobile-stats">
        <div class="mobile-stat-row">
          <div class="mobile-stat-item">
            <div class="mobile-stat-label">容量</div>
            <div class="mobile-stat-value">
              {{ useflow.usesize }} / {{ useflow.size }}
            </div>
            <div class="mobile-progress">
              <el-progress :percentage="useflow.percentagesize" />
            </div>
          </div>
          <div class="mobile-stat-item">
            <div class="mobile-stat-label">月流量</div>
            <div class="mobile-stat-value">
              {{ useflow.useflow }} / {{ useflow.flow }}
            </div>
            <div class="mobile-progress">
              <el-progress :percentage="useflow.percentageflow" />
            </div>
          </div>
        </div>
        <div class="mobile-upload">
          <el-upload
            class="upload-demo mobile"
            :disabled="!!percentage"
            action="https://jsonplaceholder.typicode.com/posts/"
            :auto-upload="true"
            :http-request="request"
            :show-file-list="false"
          >
            <el-button
              :disabled="!!percentage"
              ref="buttonRef"
              size="default"
              type="primary"
              class="mobile-upload-btn"
            >
              <el-icon :size="16">
                <Upload />
              </el-icon>
              &nbsp;
              {{ percentage ? "上传中..." + percentage + "%" : "上传文件" }}
            </el-button>
          </el-upload>
        </div>
      </div>
    </div>
    <!-- 文件列表区域 -->
    <div class="file-list-container" v-if="count" v-loading="loading">
      <!-- 桌面端表格视图 -->
      <div class="desktop-table">
        <table class="table">
          <tbody>
            <tr class="thead">
              <td scope="col" class="colbt">文件名</td>
              <td width="180" scope="col" class="text-center">文件类型</td>
              <td width="180" class="text-center" scope="col">上传时间</td>
              <td width="180" scope="col" class="text-center">文件大小</td>
              <td width="174" class="text-center" scope="col">操作</td>
            </tr>

            <tr class="thead2" v-for="(v, key) in tableDate" :key="key">
              <td class="colbt">{{ v.name }}</td>
              <td class="text-center">{{ v.type }}</td>
              <td class="text-center">{{ TimeYH2(v.createdAt) }}</td>
              <td class="text-center">{{ renderSize(Number(v.size)) }}</td>
              <td class="text-center">
                <el-tooltip
                  effect="dark"
                  content="下载链接有效期：5分钟"
                  placement="left"
                >
                  <el-button
                    :icon="Download"
                    size="default"
                    @click="download(v)"
                  >
                    下载
                  </el-button>
                </el-tooltip>
                <el-button size="default" v-show="isAdmin" @click="del(v)"
                  >删除</el-button
                >
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 移动端卡片视图 -->
      <div class="mobile-cards">
        <div class="file-card" v-for="(v, key) in tableDate" :key="key">
          <div class="card-header">
            <div class="file-name" :title="v.name">{{ v.name }}</div>
            <div class="file-type">{{ v.type || "无类型" }}</div>
          </div>
          <div class="card-body">
            <div class="file-info">
              <div class="info-item">
                <span class="info-label">上传时间:</span>
                <span class="info-value">{{ TimeYH2(v.createdAt) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">文件大小:</span>
                <span class="info-value">{{ renderSize(Number(v.size)) }}</span>
              </div>
            </div>
            <div class="card-actions">
              <el-tooltip
                effect="dark"
                content="下载链接有效期：5分钟"
                placement="top"
              >
                <el-button
                  :icon="Download"
                  size="small"
                  @click="download(v)"
                  class="action-btn"
                >
                  下载
                </el-button>
              </el-tooltip>
              <el-button
                size="small"
                v-show="isAdmin"
                @click="del(v)"
                class="action-btn delete-btn"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 分页器 -->
    <div class="pagination-container" v-if="count">
      <el-pagination
        :page-size="limit"
        :total="count"
        @current-change="change"
        :layout="paginationLayout"
        :current-page="Math.floor(offset / limit) + 1"
        class="mobile-pagination"
      ></el-pagination>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="!count"
      image="https://cdn.hterobot.com/JOY/oj_1_1/Not%20Found%20illustration.png"
      class="empty-state"
    />
  </div>
</template>

<script setup lang="ts">
import { Download, Upload } from "@element-plus/icons-vue";
import OSS from "ali-oss";
import {
  ElButton,
  ElMessage,
  ElMessageBox,
  ElNotification,
  ElUpload,
  UploadRequestOptions,
} from "element-plus";
import { debounce } from "underscore";
import { v4 } from "uuid";
import { computed, h, onMounted, ref, watch } from "vue";
import {
  asynccreateteamfile,
  asyncdelectteamfile,
  asyncgetteamfile,
  asyncgetteamflow,
  asyncupdateteamflow,
  asyncuploadAccess,
  ossupload,
} from "../../../api";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TimeYH2 } from "../../../util/time";
import { updateoss2 } from "../../../util/updateoss";
import { useStore } from "vuex";
import { Storekey } from "../../../interface";
const store = useStore(Storekey);

// const p = defineProps<{
//   isAdmin?: 0 | 1 | 2;
//   user?: Studycodemodel.Iuser;
//   flow?: Studycodemodel.Iteamflow;
//   setflow?: Function;
// }>();
const flow = ref<Studycodemodel.Iteamflow>();
async function setflow() {
  try {
    flow.value = await asyncgetteamflow({ teamid: teamid?.value });
  } catch (e) {
    flow.value = undefined;
    console.log(e);
  }
}
const user = computed(() => {
  return store.state.user;
});
const teamid = computed(() => {
  return user.value?.teamid;
});

const isAdmin = computed(() => {
  return user.value?.isAdmin;
});

const tableDate = ref<Studycodemodel.Iteamfile[]>([]);
const percentage = ref(0);

// 响应式分页布局
const paginationLayout = computed(() => {
  // 检测屏幕宽度，在小屏幕上使用简化布局
  if (typeof window !== "undefined" && window.innerWidth < 768) {
    return "prev, pager, next";
  }
  return "total, prev, pager, next, jumper";
});

async function del(V: Studycodemodel.Iteamfile) {
  if (!isAdmin.value) {
    ElMessage.error("没有权限");
  }
  ElMessageBox.confirm("确定要删除?", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "",
    type: "warning",
  })
    .then(async () => {
      try {
        await asyncdelectteamfile(V);
        if (V.url) {
          await o.value?.delete(V.url);
        }
        start();
      } catch (e) {
        ElMessage({
          message: String(e),
          type: "error",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}

const useflow = computed(() => {
  const {
    usesize = 0,
    size = 1021 * 1024 * 1024 * 5,
    useflow = 0,
  } = flow.value || {};
  const _flow = flow.value?.flow || 1021 * 1024 * 1024 * 10;
  return {
    size: renderSize(size),
    usesize: renderSize(usesize),
    flow: renderSize(_flow),
    useflow: renderSize(useflow),
    percentageflow: Math.floor((useflow / _flow) * 100),
    percentagesize: Math.floor((usesize / size) * 100),
    _usesize: usesize,
    _size: size,
    _flow: _flow,
    _useflow: useflow,
  };
});

async function download(name: Studycodemodel.Iteamfile) {
  if (useflow.value._useflow > useflow.value._flow) {
    ElMessage.error("本月团队资料流量已用完，如需帮助请联系助教老师或管理员");
    return;
  }
  const data = o.value?.signatureUrl(String(name.url), {
    expires: 300,
  });
  await asyncupdateteamflow({
    ID: flow.value?.ID,
    useflow: flow.value?.useflow,
    size: name.size,
    teamid: teamid.value,
    name: name.name,
    teamfileid: name.ID,
  });
  window.open(data, "_blank");
  setflow();
}

const upload = ref<typeof ElUpload>();
async function request(option: UploadRequestOptions) {
  if (upload.value) upload.value.clearFiles();
  if (option.file.size > 1024 * 1024 * 1024) {
    ElMessage.warning(
      "提示：文件资料大小为1G以内，如需上传更大文件请联系助教老师"
    );
    return;
  }

  if (useflow.value._usesize > useflow.value._size) {
    ElMessage.error("团队存储空间已满，如需帮助请联系助教老师或管理员");
    return;
  }
  if (option.file.name.length > 128) {
    ElMessage.error("文件名称最大长度128");
    return;
  }
  try {
    const res = await asyncuploadAccess({ teamid: teamid.value });
    const v = v4();
    const d = await updateoss2(
      [option.file],
      {
        bucket: "ojteam",
        url: `${teamid.value}/${v}/${option.file.name}`,
        res,
      },
      () => {},
      {
        progress,
      }
    );
    percentage.value = 0;
    const sp = option.file.name.split(".");
    await asynccreateteamfile({
      name: option.file.name,
      url: d.name,
      size: option.file.size,
      type: sp.length === 1 ? "" : sp.pop(),
      teamid: teamid.value,
    });
    start();
    setflow();
  } catch (e: any) {
    console.log(e);
    ElMessage.error(e);
  }
}

function progress(per: number) {
  percentage.value = Math.floor(per * 100);
}

function renderSize(value: number) {
  if (!value) {
    return "0 Bytes";
  }
  var unitArr = new Array(
    "Bytes",
    "KB",
    "MB",
    "GB",
    "TB",
    "PB",
    "EB",
    "ZB",
    "YB"
  );
  var index = 0;
  var srcsize = parseFloat(String(value));
  index = Math.floor(Math.log(srcsize) / Math.log(1024));
  var size = srcsize / Math.pow(1024, index);
  return size.toFixed(2) + unitArr[index];
}

const count = ref(0);
const offset = ref(0);
const limit = ref(10);
const loading = ref(false);
const name = ref("");
function debounce1() {
  return debounce(() => {
    let _like: [keyof Studycodemodel.Iteamfile, any] | undefined;
    if (name.value) {
      _like = ["name", name.value];
    }
    loading.value = true;
    asyncgetteamfile({
      _offset: offset.value,
      _limit: limit.value,
      _like,
      teamid: teamid.value,
    }).then((e) => {
      loading.value = false;
      tableDate.value = e.rows;
      count.value = e.count;
    });
    setflow();
  }, 300);
}
const start = debounce1();

watch([offset, limit, name], () => {
  start();
});

const o = ref<OSS>();

onMounted(async () => {
  const res = await ossupload();
  o.value = new OSS({
    region: "oss-cn-qingdao",
    accessKeyId: res.accessKeyId,
    accessKeySecret: res.accessKeySecret,
    stsToken: res.securityToken,
    bucket: "ojteam",
    refreshSTSToken: async () => {
      const info = await ossupload();
      return {
        accessKeyId: info.accessKeyId,
        accessKeySecret: info.accessKeySecret,
        stsToken: info.securityToken,
      };
    },
  });
  start();
});

function change(r: number) {
  offset.value = (r - 1) * 10;
}
</script>

<style scoped>
/* 基础样式 */
.text-right {
  text-align: right;
}

.d-inline-block {
  display: inline-block;
}

.header {
  padding-top: 10px;
}

.container-xl {
  --bs-gutter-x: 0;
  --my-home-div-height: 56px;
  padding: 12px;
}

/* 头部信息区域 */
.header-info {
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.title-text {
  font-size: 18px;
  font-weight: 600;
  margin-left: 8px;
}

.icon {
  width: 20px;
  height: 20px;
}

/* 桌面端统计信息 */
.desktop-stats {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
}

.stat-label {
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  margin-bottom: 8px;
}

.progress-wrapper {
  width: 120px;
}

.upload-section {
  margin-left: auto;
}

/* 移动端统计信息 */
.mobile-stats {
  display: none;
}

.mobile-stat-row {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.mobile-stat-item {
  flex: 1;
  background: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
}

.mobile-stat-label {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 4px;
}

.mobile-stat-value {
  font-size: 13px;
  font-weight: 500;
  margin-bottom: 8px;
}

.mobile-progress {
  width: 100%;
}

.mobile-upload {
  text-align: center;
}

.mobile-upload-btn {
  width: 100%;
  max-width: 200px;
}

/* 文件列表容器 */
.file-list-container {
  margin-bottom: 20px;
}

/* 桌面端表格 */
.desktop-table {
  display: block;
}

.table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.thead {
  background: #f8f9fa;
  font-weight: 700;
  height: 48px;
  line-height: 48px;
}

.thead2 {
  height: 56px;
  line-height: 56px;
  border-bottom: 1px solid #f0f0f0;
}

.thead2:hover {
  background: #f8f9fa;
}

.colbt {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 18px;
}

/* 移动端卡片 */
.mobile-cards {
  display: none;
}

.file-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #f0f0f0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.file-name {
  font-weight: 600;
  font-size: 16px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 12px;
}

.file-type {
  background: #e6f7ff;
  color: #1890ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.file-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.info-value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.action-btn {
  flex: 1;
  max-width: 80px;
}

.delete-btn {
  color: #ff4d4f;
  border-color: #ff4d4f;
}

.delete-btn:hover {
  background: #ff4d4f;
  color: white;
}

/* 分页器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.mobile-pagination {
  width: 100%;
}

/* 空状态 */
.empty-state {
  margin: 40px 0;
}

.upload-demo {
  height: 48px;
  display: flex;
  justify-content: end;
}

.upload-demo.mobile {
  justify-content: center;
  width: 100%;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .container-xl {
    padding: 8px;
  }

  .title-text {
    font-size: 16px;
  }

  /* 隐藏桌面端布局 */
  .desktop-stats {
    display: none;
  }

  .desktop-table {
    display: none;
  }

  /* 显示移动端布局 */
  .mobile-stats {
    display: block;
  }

  .mobile-cards {
    display: block;
  }

  /* 分页器在移动端简化 */
  .pagination-container :deep(.el-pagination) {
    justify-content: center;
  }

  .pagination-container :deep(.el-pagination .el-pager) {
    flex-wrap: wrap;
  }

  .pagination-container :deep(.el-pagination .el-pager .number) {
    min-width: 32px;
    height: 32px;
    line-height: 32px;
  }
}

@media (max-width: 480px) {
  .container-xl {
    padding: 4px;
  }

  .mobile-stat-row {
    flex-direction: column;
    gap: 8px;
  }

  .file-card {
    padding: 12px;
    margin-bottom: 8px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .file-name {
    margin-right: 0;
    margin-bottom: 4px;
  }

  .card-actions {
    flex-direction: column;
  }

  .action-btn {
    max-width: none;
    width: 100%;
  }
}
</style>
